﻿using System.Collections.Generic;
using System.Linq;
using mBlog.Data;
using mBlog.Extensions;
using mBlog.Models;
using AutoMapper;

namespace mBlog.Services
{
    public class TagService : ITagService
    {
        private mBlogContext blogContext;

        public TagService(mBlogContext context)
        {
            this.blogContext = context;
        }

        public Tag Single(long id)
        {
            var tag = blogContext.Tags.Single(t => t.Id == id);

            return tag.MapTo<Tag>();
        }

        public Tag Single(string urlName)
        {
            return blogContext.Tags.Single(t => t.UrlName == urlName)
                    .MapTo<Tag>();
        }

        public int GetPostTotalUnderTag(string tagUrlName)
        {
            var tag = blogContext.Tags.Include("Posts").Single(t => t.UrlName == tagUrlName);

            return tag.Posts.Count;
        }

        public IList<Tag> Get(string tagName)
        {
            return blogContext.Tags.Where(t => t.Name == tagName)
                    .AsEnumerable()
                    .MapTo<Tag>()
                    .ToList();
        }

        public IList<Tag> Get(int? page, int itemsPerpage)
        {

            return blogContext.Tags
                .OrderByDescending(t => t.AddedTime)
                .Skip((page ?? 0) * itemsPerpage)
                    .Take(itemsPerpage).ToList()
                    .MapTo<Tag>()
                    .ToList();
        }

        public int Count()
        {
            return blogContext.Tags.Count();
        }


        public void Update(Tag tag)
        {
            var entity = blogContext.Tags.Single(t => t.Id == tag.ID);
            if (entity != null)
            {
                entity = tag.MapTo<Data.Entities.Tag>();

                blogContext.SaveChanges();
            }
        }


        public void Delete(long id)
        {
            var t = blogContext.Tags.Single(ta => ta.Id == id );

            blogContext.Tags.Remove(t);
            blogContext.SaveChanges();
        }
    }
}
